package org.qiyu.live.im.core.server.common;



import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.MessageToMessageDecoder;
import org.qiyu.live.im.constants.ImConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * 消息解码器 ：用户获取消息实体，并将编码后的消息解码装换为对应的消息实体
 * 作者：無言
 * 时间：2024/12/2 20:49
 * 描述：永无BUG
 */
public class ImMsgDecoder extends ByteToMessageDecoder {

    private static final Logger LOGGER = LoggerFactory.getLogger(ImMsgDecoder.class);

    /**
     * 协议的开头部分的标准长度 , magic + len + code的字节长度
     */
    public final int BASE_LENGTH = 2 + 4 + 4;


    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        if (byteBuf.readableBytes() >= BASE_LENGTH) {
            if (byteBuf.readShort() != ImConstants.DEFAULT_MAGIC) {
                channelHandlerContext.close();
                return;
            }


            int code = byteBuf.readInt();
            int length = byteBuf.readInt();
            if (byteBuf.readableBytes() < length) {
                //数据包有异常
                channelHandlerContext.close();
                return;
            }


            byte[] body = new byte[length];
            byteBuf.readBytes(body);
            ImMsg imMsg = new ImMsg();
            imMsg.setCode(code);
            imMsg.setLen(length);
            imMsg.setMagic(ImConstants.DEFAULT_MAGIC);
            imMsg.setBody(body);
            list.add(imMsg);
        }
    }
}
